package com.zenithmind.common.metrics;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 业务指标收集器
 * 用于收集和暴露业务相关的监控指标
 */
@Slf4j
@Component
public class BusinessMetrics {
    
    private final MeterRegistry meterRegistry;
    private final ConcurrentHashMap<String, AtomicLong> businessCounters = new ConcurrentHashMap<>();
    
    // 预定义的计数器
    private final Counter userRegistrationCounter;
    private final Counter userLoginCounter;
    private final Counter userLoginFailureCounter;
    private final Counter apiRequestCounter;
    private final Counter apiErrorCounter;
    
    // 预定义的计时器
    private final Timer databaseQueryTimer;
    private final Timer cacheOperationTimer;
    private final Timer externalApiTimer;
    
    public BusinessMetrics(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        
        // 初始化计数器
        this.userRegistrationCounter = Counter.builder("business.user.registration")
                .description("用户注册次数")
                .register(meterRegistry);
                
        this.userLoginCounter = Counter.builder("business.user.login.success")
                .description("用户登录成功次数")
                .register(meterRegistry);
                
        this.userLoginFailureCounter = Counter.builder("business.user.login.failure")
                .description("用户登录失败次数")
                .register(meterRegistry);
                
        this.apiRequestCounter = Counter.builder("business.api.requests")
                .description("API请求总数")
                .register(meterRegistry);
                
        this.apiErrorCounter = Counter.builder("business.api.errors")
                .description("API错误总数")
                .register(meterRegistry);
        
        // 初始化计时器
        this.databaseQueryTimer = Timer.builder("business.database.query.duration")
                .description("数据库查询耗时")
                .register(meterRegistry);
                
        this.cacheOperationTimer = Timer.builder("business.cache.operation.duration")
                .description("缓存操作耗时")
                .register(meterRegistry);
                
        this.externalApiTimer = Timer.builder("business.external.api.duration")
                .description("外部API调用耗时")
                .register(meterRegistry);
        
        // 注册动态指标
        registerDynamicGauges();
    }
    
    /**
     * 记录用户注册
     */
    public void recordUserRegistration() {
        userRegistrationCounter.increment();
        log.debug("记录用户注册指标");
    }
    
    /**
     * 记录用户登录成功
     */
    public void recordUserLoginSuccess() {
        userLoginCounter.increment();
        log.debug("记录用户登录成功指标");
    }
    
    /**
     * 记录用户登录失败
     */
    public void recordUserLoginFailure() {
        userLoginFailureCounter.increment();
        log.debug("记录用户登录失败指标");
    }
    
    /**
     * 记录API请求
     */
    public void recordApiRequest() {
        apiRequestCounter.increment();
    }
    
    /**
     * 记录API错误
     */
    public void recordApiError() {
        apiErrorCounter.increment();
    }
    
    /**
     * 获取数据库查询计时器
     */
    public Timer getDatabaseQueryTimer() {
        return databaseQueryTimer;
    }
    
    /**
     * 获取缓存操作计时器
     */
    public Timer getCacheOperationTimer() {
        return cacheOperationTimer;
    }
    
    /**
     * 获取外部API计时器
     */
    public Timer getExternalApiTimer() {
        return externalApiTimer;
    }
    
    /**
     * 增加自定义业务计数器
     */
    public void incrementBusinessCounter(String counterName) {
        businessCounters.computeIfAbsent(counterName, k -> new AtomicLong(0)).incrementAndGet();
        log.debug("增加业务计数器: {}", counterName);
    }
    
    /**
     * 设置自定义业务计数器值
     */
    public void setBusinessCounter(String counterName, long value) {
        businessCounters.computeIfAbsent(counterName, k -> new AtomicLong(0)).set(value);
        log.debug("设置业务计数器: {} = {}", counterName, value);
    }
    
    /**
     * 获取自定义业务计数器值
     */
    public long getBusinessCounter(String counterName) {
        AtomicLong counter = businessCounters.get(counterName);
        return counter != null ? counter.get() : 0;
    }
    
    /**
     * 注册动态指标
     */
    private void registerDynamicGauges() {
        // 注册在线用户数指标
        Gauge.builder("business.users.online", () -> getBusinessCounter("online_users"))
                .description("在线用户数")
                .register(meterRegistry);
        
        // 注册活跃会话数指标
        Gauge.builder("business.sessions.active", () -> getBusinessCounter("active_sessions"))
                .description("活跃会话数")
                .register(meterRegistry);
        
        // 注册缓存命中率指标
        Gauge.builder("business.cache.hit.ratio", () -> {
                    long hits = getBusinessCounter("cache_hits");
                    long total = getBusinessCounter("cache_total");
                    return total > 0 ? (double) hits / total : 0.0;
                })
                .description("缓存命中率")
                .register(meterRegistry);
    }
    
    /**
     * 记录缓存命中
     */
    public void recordCacheHit() {
        incrementBusinessCounter("cache_hits");
        incrementBusinessCounter("cache_total");
    }
    
    /**
     * 记录缓存未命中
     */
    public void recordCacheMiss() {
        incrementBusinessCounter("cache_total");
    }
    
    /**
     * 设置在线用户数
     */
    public void setOnlineUsers(long count) {
        setBusinessCounter("online_users", count);
    }
    
    /**
     * 设置活跃会话数
     */
    public void setActiveSessions(long count) {
        setBusinessCounter("active_sessions", count);
    }
}
